package cn.itsource.pethome.quartz;

import org.quartz.*;
import org.springframework.boot.autoconfigure.quartz.QuartzDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * quarts定时器任务
 */
@Configuration
public class QuartzConfig {
    /**
     * quartz数据库持久化
     * @return
     */
    @Bean
    @QuartzDataSource
    @ConfigurationProperties(prefix = "spring.quartz.properties.org.quartz.datasource")
    DataSource quartzDataSource(){
        return DataSourceBuilder.create().build();
    }

    /**
     * 工作详情
     * @return
     */
    @Bean
    public JobDetail nowJob(){
        JobDetail jobDetail = JobBuilder.newJob(MyJob.class)
                .usingJobData("param", "测试一把")
                .withIdentity("myjob")
                .storeDurably()//即使没有Trigger关联时，也不需要删除该JobDetail
                .build();

        return jobDetail;
    }
    /**
     * 定时任务
     * @return
     */
    @Bean
    public Trigger trigger(){
        //调度器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("0/2 * * * * ? ");
        //触发器
        CronTrigger trigger = TriggerBuilder.newTrigger()
                .forJob(nowJob())
                .withIdentity("trigger")
                .withSchedule(cronScheduleBuilder)
                .build();
        return trigger;
    }


}
